package com.example.lotterysystem.service.activitystatus.operator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.lotterysystem.common.enums.ActivityUserStatusEnum;
import com.example.lotterysystem.dao.dataobject.ActivityUser;
import com.example.lotterysystem.mapper.ActivityUserMapper;
import com.example.lotterysystem.service.dto.TransferActivityStatusDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
public class UserOperator extends AbstractActivityOperator{

    @Autowired
    private ActivityUserMapper activityUserMapper;
    @Override
    public Integer sequence() {
        return 1;
    }

    @Override
    public Boolean checkTransfer(TransferActivityStatusDTO statusDTO) {
        Long activityId = statusDTO.getActivityId();
        List<Long> userIds = statusDTO.getUserIds();
        ActivityUserStatusEnum userStatus = statusDTO.getTargetUserStatus();
        if(activityId == null || userStatus == null || CollectionUtils.isEmpty(userIds)){
            return false;
        }
        List<ActivityUser> activityUserList = activityUserMapper.selectList(
                new QueryWrapper<ActivityUser>().
                        eq("activity_id", activityId)
                        .in("user_id", userIds));
        if(CollectionUtils.isEmpty(activityUserList)){
            return false;
        }
        for (ActivityUser user : activityUserList) {
            if(user.getStatus().equalsIgnoreCase(statusDTO.getTargetUserStatus().name())){
                return false;
            }
        }
        return true;
    }

    @Override
    public Boolean transfer(TransferActivityStatusDTO statusDTO) {
        try {
            activityUserMapper.updateUsersStatus(statusDTO.getActivityId(),
                    statusDTO.getUserIds(),
                    statusDTO.getTargetUserStatus().name());
            return true;
        } catch (Exception e){
            return false;
        }
    }
}
